package chances.wechat.service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BaseService {
    Logger logger = LoggerFactory.getLogger("remoteCallLogger");
    Logger error = LoggerFactory.getLogger("error");
    
    public static final MediaType JSON = MediaType
            .parse("application/json; charset=utf-8");
    
    @Value("${okhttp3.connect.timeout:5}")
    private int connectTimeOut;

    @Value("${okhttp3.read.timeout:10}")
    private int readTimeOut;
    
    public String getMethod(String url) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(connectTimeOut, TimeUnit.SECONDS)
                .readTimeout(readTimeOut, TimeUnit.SECONDS).build();

        Request request = new Request.Builder().url(url).build();
        logger.info("getmethod url:" + url);
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String result = response.body().string();
            logger.info("getMethod result:" + result);
            return result;
        } catch (Exception e) {
            error.error(e.getMessage(), e);
            return null;
        }
    }

    public String postMethod(String url, String json) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(connectTimeOut, TimeUnit.SECONDS)
                .readTimeout(readTimeOut, TimeUnit.SECONDS).build();
        logger.info("postmethod url:{},json:{}", url, json);
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(url).post(body).build();
        try {
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            logger.info("postMethod result:" + result);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
